package org.jeecg.modules.wms.goods.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.wms.goods.entity.WmsCargoOwners;
import org.jeecg.modules.wms.goods.mapper.WmsCargoOwnersMapper;
import org.jeecg.modules.wms.goods.service.IWmsCargoOwnersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description: 货主表
 * @Author: jeecg-boot
 * @Date:   2025-09-02
 * @Version: V1.0
 */
@Service
public class WmsCargoOwnersServiceImpl extends ServiceImpl<WmsCargoOwnersMapper, WmsCargoOwners> implements IWmsCargoOwnersService {

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 货主添加
     *
     * @param wmsCargoOwners
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(WmsCargoOwners wmsCargoOwners) {

        wmsCargoOwners.setOwnerCode(generateOwnerCode());
        // 保存到数据库
        save(wmsCargoOwners);

    }
    /**
     * 生成货主编码
     * */
    private String generateOwnerCode() {
        // 编码规则 c+5位序号，序号使用redis自增

        // key
        String key = "WMS_CARGO_OWNERS_CODE";

        long incr = 0;

        try {
            // 调用redis的incr函数
            // key用文档上的 delta自增量
            incr = redisUtil.incr(key, 1);
        } catch (Exception e) {
            // 生成编号错了抛出异常 统一用JeecgBootException
            throw new JeecgBootException("生成货主编码出错");
        }
        // 5位序号 使用String.format方法
        String code = String.format("%05d", incr);

        return "c" + code;

    }
}
